<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/25
 * Time: 9:47
 */

namespace app\share\model;
use app\common\model\IcmpPing;
use think\Db;
use think\Model;

class PingRecord extends Model
{
    protected $STATUS_ONE   = 1;//网络畅通
    protected $STATUS_TWO   = 2;//网络超时
    protected $STATUS_THREE = 3;//ip错误80关闭

    public function __construct()
    {
        parent::__construct();
        $this->php_excel = new PhpExecl();
        $this->icmp = new IcmpPing();
    }
    public function timePingList($table,$where)
    {
        $down_data = Db::table( 'wisdom_'.$table )
            ->join( 'ip_store','wisdom_'.$table.'.ping_ip_id = ip_store.ip_id' )
            ->join( 'time_log','wisdom_'.$table.'.ping_sort = time_log.time_sort' )
            ->where( $where )
            ->order(['ping_id'=>'desc'])
            ->buildSql();

        $down_data = Db::table( $down_data."a" )
            ->field( "count(*) as count, ping_ip_id, net_name, ip_address, ping_time, ping_status, ping_sort, interval_time" )
            ->group('ping_ip_id,ping_status')
            ->order(['ping_id'=>'desc'])
            ->select();
        returnJson(200,  "success", $down_data)->send();die;
    }
    public function allIp($data)
    {
        $where['company_id'] = $data['company_id'];
        $where['depart_id'] = $data['depart_id'];
        $database = Db::name("ip_store")
            ->field("ip_id,ip_address")
            ->where($where)
            ->Select();
        returnJson(200,  "success", $database)->send();die;
    }
    public function allCompany($id)
    {
        $data = Db::name("company")
            ->field("company_id,company_name,p_id")
            ->where(['p_id'=>$id])
            ->order(['company_id'=>'asc'])
            ->select();
        if($id != 0)
        {
            foreach($data as $k=>$v)
            {
                $where['company_id'] = $v['p_id'];
                $where['depart_id'] = $v['company_id'];
                $res = Db::name("ip_store")->where($where)->count();
                if(!$res)
                {
                    unset($data[$k]);
                }
            }
        }

        returnJson(200,  "success", $data)->send();die;
    }
    public function moreDown($page,$size)
    {
        $data = Db::name("more_down_month")
            ->order(['more_id'=>'desc'])
            ->page($page, $size)
            ->select();
        $total = Db::name("more_down_month")
            ->order(['more_id'=>'desc'])
            ->count();
        $list['total']  = $total;
        $list['page']   = $page;
        $list['size']   = $size;
        $list['domain']  = config("excel_domain")."historyexcel/";
        $list['data']   = $data;
        returnJson(200,  "success", $list)->send();die;
    }
    //定时时间,月初1号1点执行
    public function downMore()
    {
        //计算上月时间,月初执行,-5天
        $time = time() - 5*24*60*60;
        $month = date('Y-m',$time);
        $data = Db::name("ip_store")
            ->field("ping_ip_id,net_name,ping_month,ping_ip_day,ping_status,ip_address,company_id,depart_id")
            ->join("ping_success_day_log","wisdom_ip_store.ip_id = ping_success_day_log.ping_ip_id")
            ->order(['ping_ip_id'=>'desc'])
            ->where(['ping_month'=>$month])
            ->select();
        foreach($data as $k=>$v)
        {
            $res = Db::name("company")->field("company_name")->where(['company_id'=>$v['company_id']])->find();
            $data[$k]['company_name'] = $res['company_name'];
            unset($data[$k]['company_id']);
            $res1 = Db::name("company")->field("company_name")->where(['company_id'=>$v['depart_id']])->find();
            $data[$k]['depart_name'] = $res1['company_name'];
            unset($data[$k]['depart_id']);
            if($v['ping_status'] === 1)
            {
                $status = "畅通";
            }else
            {
                $status = "断点";
            }
            $data[$k]['ping_status'] = $status;
        }
        return $this->php_excel->downMore($data,$month);
    }
    public function onlyIpDetail($ip,$page,$size)
    {
        $ip_detail = Db::name("ip_store")
            ->field("ip_id,ip_address,net_name,ip_server,ip_remark,ip_update,ip_user,ip_status,company_id,depart_id")
            ->where(['ip_address'=>$ip])
            ->find();

        //用户
        $res1 = Db::name("admin_user")->field("name")->where(['admin_id'=>$ip_detail['ip_user']])->find();
        $ip_detail['user_name'] = $res1['name'];
        unset($ip_detail['ip_user']);
        //服务商
        $res1 = Db::name("server_name")->field("server_name")->where(['server_id'=>$ip_detail['ip_server']])->find();
        $ip_detail['server_name'] = $res1['server_name'];
        unset($ip_detail['ip_server']);
        //单位
        $res1 = Db::name("company")->field("company_name")->where(['company_id'=>$ip_detail['company_id']])->find();
        $ip_detail['company_name'] = $res1['company_name'];
        unset($ip_detail['company_id']);
        //部门
        $res1 = Db::name("company")->field("company_name")->where(['company_id'=>$ip_detail['depart_id']])->find();
        $ip_detail['depart_name'] = $res1['company_name'];
        unset($ip_detail['depart_id']);


        $data = Db::name("ip_store")
            ->field("ping_ip_day,ping_status")
            ->join("ping_success_day_log","wisdom_ip_store.ip_id = ping_success_day_log.ping_ip_id")
            ->where(['ip_address'=>$ip])
            ->order(['add_time'=>'desc'])
            ->page($page, $size)
            ->select();

        $total = Db::name("ip_store")
            ->join("ping_success_day_log","wisdom_ip_store.ip_id = ping_success_day_log.ping_ip_id")
            ->where(['ip_address'=>$ip])
            ->count();
        $list['total']  = $total;
        $list['page']   = $page;
        $list['size']   = $size;
        $list['data']   = $data;
        returnJson(200,  "success", compact("ip_detail","list"))->send();die;

    }


    public function SouIp($ip,$sort)
    {
        $table_end = $this->tableName(substr( $sort, 0, 10 ));
        //获取最新批次的表名
        $table_name = "ping_record_".$table_end;

        $data = Db::name($table_name)
            ->field("ip_id, ip_server, net_name,ip_address,ping_status,company_id,depart_id")
            ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
            ->where( ['ip_id'=>$ip,'ping_sort'=>$sort] )
            ->find();

        $res1 = Db::name("company")->field("company_name")->where(['company_id'=>$data['company_id']])->find();
        $data['company_name'] = $res1['company_name'];
        $res2 = Db::name("company")->field("company_name")->where(['company_id'=>$data['depart_id']])->find();
        $data['depart_name'] = $res2['company_name'];
        $res3 = Db::name("server_name")->field("server_name")->where(['server_id'=>$data['ip_server']])->find();
        $data['server_name'] = $res3['server_name'];

        $where['company_id'] = $data['company_id'];
        $where['depart_id'] = $data['depart_id'];
//        $where['ip_server'] = $data['ip_server'];
        $where['ping_sort'] = $sort;
        $where['ping_status'] = 1;

        $ping_success = Db::name($table_name)
            ->field("ip_id, ip_server, net_name,ip_address,ping_status,company_id,depart_id")
            ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
            ->where( $where )
            ->count();
        $data['ping_success'] = $ping_success;
        $where['ping_status'] = 2;

        $ping_error = Db::name($table_name)
            ->field("ip_id, ip_server, net_name,ip_address,ping_status,company_id,depart_id")
            ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
            ->where( $where )
            ->count();
        $data['ping_error'] = $ping_error;




        returnJson(200,  "success", $data)->send();die;
    }
    public function companyDepart($id)
    {
        //部门是否存在
        $res2 = Db::name("company")
            ->where(['company_id'=>$id,'p_id'=>0])->count();
        if(!$res2)
        {
            returnJson(-1200,  "单位ID".$id."不存在")->send();die;
        }
        $data = Db::name("company")
            ->field("company_id,company_name")
            ->order(['sort'=>'asc'])
            ->where(['p_id'=>$id])
            ->select();
        returnJson(200,  "success", $data)->send();die;

    }

    public function listPart()
    {
        $res = Db::name("company")
            ->field("company_id,company_name")
            ->order(['sort'=>'asc'])
            ->where(['p_id'=>0])
            ->select();
        returnJson(200,  "success",$res)->send();die;
    }
    public function listCompany($page,$size)
    {
        $res = Db::name("company")
            ->order(['sort'=>'asc'])
            ->page($page, $size)
            ->where(['p_id'=>0])
            ->select();
        foreach($res as $k=>$v)
        {
            $children = Db::name("company")
                ->order(['sort'=>'asc'])
                ->where(['p_id'=>$v['company_id']])
                ->select();
            $res[$k]['children']=$children;
        }
        $total = Db::name("company")->where(['p_id'=>0])->count();
        $list['total']  = $total;
        $list['page']   = $page;
        $list['size']   = $size;
        $list['data']   = $res;
        returnJson(200,  "success",$list)->send();die;

    }
    public function deleteCompany($id)
    {
        $res1 = Db::name("company")->where(['p_id'=>$id])->count();
        if($res1)
        {
            returnJson(-1200,  "该单位下面有部门存在,不能直接删除")->send();die;
        }
//        $res2 = Db::name("ip_store")->where(['company_id'=>$id])->count();
//        if($res2)
//        {
//            returnJson(-1200,  "该单位存在ip数据,不能删除")->send();die;
//        }
        $res = Db::name("company")->where(['company_id'=>$id])->delete();
        if($res)
        {
            returnJson(200,  "删除成功")->send();die;
        }else
        {
            returnJson(-1200,  "该数据不存在")->send();die;
        }
    }
    public function editCompany($id,$p_id,$data)
    {
        $where['company_name'] = $data['company_name'];
        $where['company_id'] = ['NEQ',$id];
        $where['p_id'] = $p_id;
        $res = Db::name("company")->where($where)->count();
        if($res)
        {
            returnJson(-1200,  $data['company_name']."已经存在")->send();die;
        }
        Db::name("company")
            ->where(['company_id'=>$id])
            ->update($data);
        returnJson(200,  "编辑成功")->send();die;


    }

    public function addCompany($data)
    {
        //去重
        if(!isset($data['p_id']) || $data['p_id'] == 0)
        {
            $res1 = Db::name("company")
                ->where(['company_name'=>$data['company_name'],'p_id'=>0])
                ->count();
            if($res1)
            {
                returnJson(-1200,  $data['company_name']."已经存在")->send();die;
            }
        }else
        {
            $where['company_name'] = $data['company_name'];
            $where['p_id'] = $data['p_id'];
            $res1 = Db::name("company")
                ->where($where)
                ->count();
            if($res1)
            {
                returnJson(-1200,  $data['company_name']."已经存在")->send();die;
            }
        }


        Db::name("company")->insert($data);
        returnJson(200,  "添加成功")->send();die;

    }
    //获取某一天的时间格式
    public function appointDay($time)
    {
        $dateStr =  date('Y-m-d', $time);
        return $dateStr;
    }
    //获取指定时间戳0点的时间戳2019-10-29 00:00:00
    public function timeStart($time)
    {
        $dateStr =  date('Y-m-d', $time);
        return strtotime( $dateStr );
    }
    //获取指定时间戳24点的时间戳2019-10-30 00:00:00
    public function timeEnd($time)
    {
        $dateStr =  date('Y-m-d', $time);
        return strtotime( $dateStr ) + 86400;
    }
    //定时任务,每日晚23点执行
    public function timeAddPing()
    {
        $start_time = time();
        //获取今日表名称
        $table_end = $this->tableName(time());
        $table_name = "ping_record_".$table_end;
        //代表天得数据时间性
        $day = date("Ymd",time());
        $data_now =  Db::table( 'wisdom_'.$table_name )
            ->order(["ping_status"=>"asc"])
            ->buildSql();
        $data_now = Db::table($data_now . "a")
            ->field("ping_ip_id,ping_status")
            ->order(['ping_status'=>'desc'])
            ->group('ping_ip_id')
            ->select();
        $ping_log = [];
        $time = time();
        foreach($data_now as $k=>$v)
        {
            $ping_log['ping_ip_id']   =  $v['ping_ip_id'];
            $ping_log['ping_status']  =  $v['ping_status'];
            $ping_log['ping_ip_day']  =  $day;
            $ping_log['add_time']     =  $time;
            Db::name("ping_success_day_log")->insert($ping_log);
        }
        //记录当天日志
        $log['sum'] = count($data_now);
        $log['ping_day'] = $day;
        $log['add_time'] = $time;
        $log['real_sum'] = Db::name("ping_success_day_log")->where(['ping_ip_day'=>$day])->count();
        Db::name("ping_day_log")->insert($log);
        if($log['sum'] == $log['real_sum'])
        {
            $log_ping_day = "执行成功";
        }else
        {
            $log_ping_day = "执行失败";
        }
        $end_time = time()-$start_time;
        echo $log_ping_day.",执行时间".$end_time."秒   ";
    }

    //手动执行任务,每日晚23点执行
    public function manualTimeAddPing($day)
    {
        $start_time = time();
        //手动执行前,必须删除历史记录
        Db::name("ping_success_day_log")->where(['ping_ip_day'=>$day])->delete();
        //获取今日表名称
        $table_end = $this->tableName(strtotime($day));
        $table_name = "ping_record_".$table_end;

        $data_now =  Db::table( 'wisdom_'.$table_name )
            ->order(["ping_status"=>"asc"])
            ->buildSql();
        $data_now = Db::table($data_now . "a")
            ->field("ping_ip_id,ping_status")
            ->order(['ping_status'=>'desc'])
            ->group('ping_ip_id')
            ->select();
        $ping_log = [];
        $ping_month = date('Ym',time());
        foreach($data_now as $k=>$v)
        {
            $ping_log['ping_ip_id']   =  $v['ping_ip_id'];
            $ping_log['ping_status']  =  $v['ping_status'];
            $ping_log['ping_ip_day']  =  $day;
            $ping_log['add_time']     =  strtotime($day) + 1000;
            $ping_log['ping_month']   =  $ping_month;
            Db::name("ping_success_day_log")->insert($ping_log);
        }
        //记录当天日志
        $log['sum'] = count($data_now);
        $log['ping_day'] = $day;
        $log['add_time'] = time();
        $log['real_sum'] = Db::name("ping_success_day_log")->where(['ping_ip_day'=>$day])->count();
        Db::name("ping_day_log")->insert($log);
        if($log['sum'] == $log['real_sum'])
        {
            $log_ping_day = "执行".$log['sum']."条数据成功";
        }else
        {
            $log_ping_day = "执行失败";
        }
        $end_time = time()-$start_time;
        returnJson(200,  "success",$log_ping_day.",执行时间".$end_time."秒")->send();die;
    }

    public function historyDownLoad( $table, $where, $page, $size, $type)
    {
        if($type == 1)
        {
            $down_data = Db::table( 'wisdom_'.$table )
                ->join( 'ip_store','wisdom_'.$table.'.ping_ip_id = ip_store.ip_id' )
                ->join( 'time_log','wisdom_'.$table.'.ping_sort = time_log.time_sort' )
                ->where( $where )
                ->order(['ping_id'=>'desc'])
                ->buildSql();

            $down_data = Db::table( $down_data."a" )
                ->field( "count(*) as count, ping_ip_id, net_name, ip_address, ping_time, ping_status, ping_sort, interval_time" )
                ->group('ping_ip_id,ping_status')
                ->order(['ping_id'=>'desc'])
                ->page($page, $size)->select();

            $total= Db::name( $table )
                ->join( 'ip_store','wisdom_'.$table.'.ping_ip_id = ip_store.ip_id' )
                ->join( 'time_log','wisdom_'.$table.'.ping_sort = time_log.time_sort' )
                ->group('ping_ip_id,ping_status')
                ->where( $where )
                ->count();
            $ping['total']  = $total;
            $ping['page']   = $page;
            $ping['size']   = $size;
            $ping['data']   = $down_data;
            returnJson(200,  "success", $ping)->send();die;
        }else
        {
            $down_data = Db::table( 'wisdom_'.$table )
                ->join( 'ip_store','wisdom_'.$table.'.ping_ip_id = ip_store.ip_id' )
                ->join( 'time_log','wisdom_'.$table.'.ping_sort = time_log.time_sort' )
                ->where( $where )
                ->order(['ping_id'=>'desc'])
                ->buildSql();
            $down_data = Db::table( $down_data."a" )
                ->field( "count(*) as count,net_name, ip_address, ping_time, ping_status, ping_sort, interval_time" )
                ->group('ping_ip_id,ping_status')
                ->order(['ping_id'=>'desc'])
                ->select();
            return $this->php_excel->downData($down_data);
        }

    }

    //获取批次
    protected function pingSort()
    {
        $ping_sort = Db::name("time_log")
            ->field("time_sort")
            ->order(['time_id'=>'desc'])
            ->find();
        return $ping_sort;
    }
    public function timeShow( $page,$size )
    {
        $ping_sort = $this->pingSort();
        $time_sort  = $ping_sort['time_sort'];
        $table_end = $this->tableName(substr( $time_sort, 0, 10 ));
        //获取最新批次的表名
        $table_name = "ping_record_".$table_end;

        $res = Db::name($table_name)
            ->field( "ping_time, net_name, ip_address, ping_status" )
            ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
            ->order( ['ping_time'=>'asc'] )
            ->where( ['ping_sort' => $time_sort] )
            ->page( $page, $size )
            ->select();

        $total = Db::name($table_name)
            ->where( ['ping_sort' => $time_sort] )
            ->count();
        $ping['total']  = $total;
        $ping['page']   = $page;
        $ping['size']   = $size;
        $ping['data']   = $res;
        returnJson(200,  "success",$ping)->send();die;
    }
    public function workDetail()
    {
        $ping_sort = $this->pingSort();
        $time_sort  = $ping_sort['time_sort'];
        $table_end = $this->tableName(substr( $time_sort, 0, 10 ));
        //获取最新批次的表名
        $table_name = "ping_record_".$table_end;
        $sum = Db::name($table_name)->where(['ping_sort'=>$time_sort])->count();
        $right = Db::name($table_name)
            ->where(['ping_sort'=>$time_sort,'ping_status'=>1])
            ->count();
        $error = Db::name($table_name)
            ->where(['ping_sort'=>$time_sort,'ping_status'=>2])
            ->count();
        $last_time = Db::name($table_name)
            ->field("ping_time")
            ->where(['ping_sort'=>$time_sort])
            ->order( [ 'ping_id'=>'desc' ] )
            ->find();
        $data['sum'] = $sum;
        $data['right'] = $right;
        $data['error'] = $error;
        $data['last_time'] = $last_time['ping_time'];
        returnJson(200,  "success", $data)->send();die;

    }
    public function onlyDetail($data)
    {
        $ping_sort = $data['ping_sort'];
        $table_end = $this->tableName(substr( $ping_sort, 0, 10 ));
        $table_name = "ping_record_".$table_end;
        $where['depart_id'] = $data['depart_id'];
//        $where['ip_server'] = $data['server_id'];
        $where['company_id'] = $data['company_id'];
//        $where['ping_status'] = $data['ping_status'];
        $where['ping_sort'] = $data['ping_sort'];
        $data = Db::name($table_name)
            ->field("ip_id, net_name,ip_address,ping_status,company_id,depart_id")
            ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
            ->where( $where )
            ->select();
        foreach($data as $k=>$v)
        {
            $res1 = Db::name("company")->field("company_name")->where(['company_id'=>$v['company_id']])->find();
            $data[$k]['company_name'] = $res1['company_name'];
            $res2 = Db::name("company")->field("company_name")->where(['company_id'=>$v['depart_id']])->find();
            $data[$k]['depart_name'] = $res2['company_name'];

        }
        returnJson(200,  "success", $data)->send();die;

    }

    public function timeDetail()
    {
        $ping_sort = $this->pingSort();
        $time_sort  = $ping_sort['time_sort'];
        $table_end = $this->tableName(substr( $time_sort, 0, 10 ));
        //获取最新批次的表名
        $table_name = "ping_record_".$table_end;
        //查询最后一次时间
        $last_time = Db::name($table_name)
            ->where(['ping_sort'=>$time_sort])
            ->order( [ 'ping_id'=>'desc' ] )
            ->value("ping_time");
        //获取单位
        $company = Db::name("company")
            ->field("company_id,company_name")
            ->where(['p_id'=>0])
            ->select();

        //单位server
        $company_data = [];
        foreach($company as $k1=>$v1)
        {
            $where_server[ 'company_id' ] = $v1['company_id'];
            $res_server = Db::name("ip_store")
                ->where(['company_id'=>$v1['company_id']])
                ->count();
            if(!$res_server)
            {
                   continue;
            }
            //部门
            $res_depart = Db::name("company")
                ->field("company_id,company_name")
                ->where(['p_id'=>$v1['company_id']])
                ->select();
            $depart_data = [];
            foreach($res_depart as $k2=>$v2)
            {
                $where11['depart_id']  = $v2['company_id'];
                $where11['company_id'] = $v1['company_id'];

                $res1_server = Db::name("ip_store")
                    ->where($where11)
                    ->count();
                if(!$res1_server)
                {
                    continue;
                }

                $where_server[ 'ping_sort' ] = $time_sort;
                $where_server[ 'ping_status' ] = 1;
                $where_server[ 'depart_id' ] = $v2['company_id'];

                $data_right = Db::name($table_name)
                    ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
                    ->where( $where_server )
                    ->count();
                $where_server[ 'ping_status' ] = 2;
                $data_error = Db::name($table_name)
                    ->join( 'ip_store','wisdom_'.$table_name.'.ping_ip_id = ip_store.ip_id' )
                    ->where( $where_server )
                    ->count();
                $depart_data[]=[
                    'depart_id'=>$v2['company_id'],
                    'depart_name'=>$v2['company_name'],
                    'status_right'=>$data_right,
                    'status_error'=>$data_error
                ];

            }
            $company_data[]=[
                'company_id'=>$v1['company_id'],
                'company_name'=>$v1['company_name'],
                'status_right'=> array_sum(array_column($depart_data, 'status_right')),
                'status_error'=>  array_sum(array_column($depart_data, 'status_error')),
                'children'=>$depart_data,
            ];
        }


        $data['ping_sort'] = $time_sort;
        $data['last_time'] = $last_time;
        $data['server_data'] = $company_data;
        returnJson(200,  "success", $data)->send();die;
    }
    public function setDel($id)
    {
        $where['set_id'] = $id;
        $set_status = Db::name("time_set")->where($where)->value("set_status");
        if($set_status)
        {
            if($set_status === 1)
            {
                returnJson(-1002,  "该规则正在启用中,请禁用后再删除")->send();die;
            }
        }else
        {
            returnJson(-1002,  "数据不存在")->send();die;
        }
        $res = Db::name("time_set")->where($where)->delete();
        if($res)
        {
            returnJson(200,  "删除成功")->send();die;
        }else
        {
            returnJson(-1002,  "数据不存在")->send();die;
        }

    }
    public function setDisplay($id,$status)
    {
        if($status==1)
        {
            $is_update = $this->STATUS_TWO;
        }else
        {
            $is_update = $this->STATUS_ONE;
            $res = Db::name("time_set")->where(['set_status'=>$this->STATUS_ONE])->count();
            if($res > 0)
            {
                returnJson(-2005,  "已有定时任务启动,请先关闭后再启用")->send();die;
            }
        }
        $ping['set_status'] = $is_update;
        $where['set_id'] = $id;
        $res = Db::name("time_set")->where($where)->update($ping);
        if($res)
        {
            returnJson(200,  "修改成功")->send();die;
        }else
        {
            returnJson(200,  "数据未修改")->send();die;
        }

    }
    public function setShow($page,$size)
    {
        $res = Db::name("time_set")
              ->order(['set_status','set_id'=>'desc'])
              ->page($page, $size)
              ->select();
        $total = Db::name("time_set")->count();
        $ping['total']  = $total;
        $ping['page']   = $page;
        $ping['size']   = $size;
        $ping['data']   = $res;
        returnJson(200,  "success",$ping)->send();die;
    }
    public function setUpdateDate( $id, $data )
    {
        $res = Db::name( "time_set" )
            ->where( ['set_id'=>$id] )
            ->update( $data );
        if($res)
        {
            returnJson(200,  "自动化测试规则编辑成功")->send();die;
        }else
        {
            returnJson(-2009,  "规则ID异常")->send();die;
        }


    }
    public function setAddDate($data)
    {
        $res = Db::name("time_set")->insert($data);
        if($res)
        {
            returnJson(200,  "自动化测试规则添加成功")->send();die;
        }
    }
    public function setOnline($where)
    {
        $res = Db::name("time_set")->where($where)->count();
        if($res)
        {
            return TRUE;
        }else
        {
            return FALSE;
        }
    }
    public function setStatus($where)
    {
        $res = Db::name("time_set")->where($where)->count();
        if($res)
        {
            returnJson(-1002,  "已有定时任务启动,请先关闭后再设置开启")->send();die;
        }
    }
    //获取毫秒时间
    protected function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    //获取时间段判断当前的时分是否在指定的时间段内
    protected function getTime($start,$end)
    {
        $date= date('H:i');
        $curTime = strtotime($date);//当前时分
        $assignTime1 = strtotime($start);//获得指定分钟时间戳，00:00
        $assignTime2 = strtotime($end);//获得指定分钟时间戳，01:00
        $result = 0;
        if($curTime>$assignTime1&&$curTime<$assignTime2){
            $result = 1;
        }
        return $result;
    }
    //28百万测试数据插入
    public function testDataInsert()
    {
        ini_set('max_execution_time','0');
        $data['ping_ip_id'] = 1058;
        $data['ping_time'] = 1572432173;
        $data['ping_status'] = 2;
        $data['ping_sort'] = "1572432171637";
        $a = 1;
        while( $a < 300)
        {
            Db::name("ping_record_30")->insert($data);
            $a++;
        }
        echo "执行完毕";
    }
    //定时请求ping的规则设置添加
    public function pingRule()
    {
        ini_set('max_execution_time','0');
        //获取定时任务规则
        $rule_data = Db::name("time_set")
                     ->field("set_day, set_start_time, set_end_time, set_holiday_status, interval_time")
                     ->where(['set_status'=>$this->STATUS_ONE])
                     ->order(['set_id'=>'desc'])
                     ->find();
        if(empty($rule_data))
        {
            echo date("H:i:s")."定时任务未启用!   ";die;
        }
//        //获取ping的间隔时间int(10)
        $interval_time = intval($rule_data['interval_time']);
        //获取上一次ping最后一条记录接收时间
        $interval_time_sort = Db::name("time_log")
            ->field("time_sort, ping_num")
            ->order( [ 'time_id'=>'desc' ] )
            ->find();
        if($interval_time_sort)
        {
            $time_sort = $interval_time_sort['time_sort']; //最后1次批次
            $table_end = $this->tableName(substr( $time_sort, 0, 10 ));
            //获取最新批次的表名
            $table_name = "ping_record_".$table_end;
            //获取log表最新批次,若不一致,则上次定时还在执行
            $new_sort = Db::name($table_name)
                ->field("ping_sort")
                ->order( [ 'ping_time'=>'desc' ] )
                ->find();
            if($new_sort)
            {
                if($new_sort['ping_sort'] == $time_sort){}else
                {
                    echo date("H:i:s")."上个批次为".date("YmdHis", substr( $new_sort['ping_sort'], 0, 10 ))."的定时任务正在执行中!   ";die;
                }
            }
            $last_time = Db::name($table_name)
                ->field("ping_time")
                ->where(['ping_sort'=>$time_sort])
                ->order( [ 'ping_time'=>'desc' ] )
                ->find();
            if($last_time)
            {
                $last_time_implement = $last_time['ping_time'];
                $delayed_time = time() - $last_time_implement - $interval_time*60;
                if( $delayed_time < 0 )
                {
                    echo date("H:i:s")."定时任务需要间隔".$interval_time."分钟再执行!   ";die;
                }
            }
        }
        //周几规则
        $weekarray=array("日","一","二","三","四","五","六");
        $current_day = date("w");
        $week_array  = explode(",", $rule_data['set_day']);
        if(!in_array($current_day,$week_array,TRUE))
        {
            echo date("H:i:s")."星期".$weekarray[$current_day]."定时任务不执行!   ";die;
        }
        //判断执行时间段,下周要进行细节时间处理问题是:时间段格式怎么存
        $rule_time = $this->getTime( $rule_data['set_start_time'],$rule_data['set_end_time'] );
        if( $rule_time === 0 )
        {
            echo date("H:i:s")."定时任务在".$rule_data['set_start_time']."-".$rule_data['set_end_time']."不执行!   ";die;
        }

        //节假日不执行,下周再加这个规则
        //正常工作日对应结果为 0, 法定节假日对应结果为 1, 节假日调休补班对应的结果为 2，休息日对应结果为 3
//        if($rule_data['set_holiday_status'] == $this->STATUS_TWO)
//        {
//            $date = date("Ymd",time());
//            $url = "http://api.goseek.cn/Tools/holiday?date=".$date;
//            $res = curl($url);    //json格式，前端需要直接提供
//            $res = json_decode($res,true);   //数组格式，方便后端判断
//            if($res['data'] === $this->STATUS_ONE)
//            {
//                echo date("H:i:s")."法定节假日定时任务不执行!   ";die;
//            }
//        }

        $this->pingAllIp( $interval_time );
    }
    //14.ping网络状态，ip地址库所有ip
    protected function pingAllIp( $interval_time )
    {
        //导入数据
        $start_time = $this->msectime();
        $data_all_ip = Db::name("ip_store")
                     ->field("ip_id,ip_address")
                     ->where(['ip_status'=>$this->STATUS_ONE])
                     ->order(['ip_id'=>'desc'])
                     ->select();
        if(empty($data_all_ip))
        {
            echo date("H:i:s")."网络服务地址尚未添加!   ";die;
        }
        $sum_ip = count($data_all_ip);
        //毫秒作为导入批次
        $sort = $start_time;
        //循环检测
        $num = 0;
//        dump($data_all_ip);die;
        foreach ($data_all_ip as $k=>$v) {
            $id = $v['ip_id'];
            $ip    = $v['ip_address'];
            ++$num;
            $this->pingOneIp($ip,$id,$sort);
        }
        //获取执行时间
        $time =  $this->msectime() - $start_time;
        $ping_result['sum_ip']  = $sum_ip;
        $ping_result['ping_num'] = $num;
        $ping_result['time_ping'] = $time."ms";
        $ping_result['time_sort'] = $start_time;
        $ping_result['interval_time'] = $interval_time;
        //记录定时任务日志表
        if($sum_ip == $num)
        {
            $ping_result['time_status'] = $this->STATUS_ONE;
            $status = "成功";
        }else
        {
            $ping_result['time_status'] = $this->STATUS_TWO;
            $status = "失败";
        }
        Db::name("time_log")->insert($ping_result);
        echo '***'.date("H:i:s")."当前定时任务执行".$status.",执行时间:".$time."ms***   ";
    }
    //获取当前表后缀
    public function tableName($time)
    {
        $timestamp = $time;
        $date = date('d',$timestamp);
        $date_first = substr( $date, 0, 1 );
        if($date_first === "0")
        {
            $table_name = substr( $date, 1, 1 );
        }else
        {
            $table_name = $date;
        }
        return $table_name;
    }
    protected function pingOneIp($ip,$id,$sort)
    {
        $url = "http://127.0.0.1/ping/public/ping.php/";
        $url = $url."share/ping_ip/pingAddress?address=".$ip;  

        // $url = config('excel_domain')."ping.php/share/ping_ip/pingAddress?address=".$ip;
        $res = curl($url);
        if($res === "Timeout")
        {
            $result['ping_status'] = $this->STATUS_TWO;
        }else if(is_numeric($res))
        {
            $result['ping_status'] = $this->STATUS_ONE;
        }else
        {
            $result['ping_status'] = $this->STATUS_TWO;
        }

//        $ping_cmd = "ping -c 1 -w 1 " . $ip;
//        exec($ping_cmd, $info);
//        if($info == null)
//        {
//            $result['ping_status'] = $this->STATUS_THREE;
//        }else
//        {
//            //判断是否丢包
//            $str1 = $info['4'];
//            $str2 = "1 packets transmitted, 1 received, 0% packet loss, time 0ms";
//            if(trim($str1)===$str2)
//            {
//                $result['ping_status'] = $this->STATUS_ONE;
//            }else
//            {
//                $result['ping_status'] = $this->STATUS_TWO;
//            }
//        }

        $result['ping_ip_id'] = $id;
        $result['ping_time']  = time();
        $result['ping_sort']  = $sort;
        $day_time = substr( $sort, 0, 10 );
        $table_name = "ping_record_".$this->tableName($day_time);
        Db::name($table_name)->insert($result);
    }

}